<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入广告标题"/>
      <el-input v-model="listQuery.content" clearable class="filter-item" style="width: 200px;" placeholder="请输入广告内容"/>
      <el-select v-model="listQuery.position" clearable class="filter-item" placeholder="请选择广告位置">
        <el-option :value="1" label="首页"/>
        <el-option :value="2" label="中间"/>
        <el-option :value="3" label="良机优品页面"/>
        <el-option :value="4" label="抢购"/>
        <el-option :value="5" label="分类-新品展示"/>
        <el-option :value="6" label="有好礼"/>
        <el-option :value="7" label="首页广告"/>
        <el-option :value="8" label="首页弹窗"/>
        <el-option :value="9" label="通用配件"/>
        <el-option :value="10" label="潮品"/>
        <el-option :value="11" label="首页特权专栏"/>
        <el-option :value="12" label="平板专栏"/>
        <el-option :value="13" label="手机专栏"/>
        <el-option :value="14" label="启动页广告"/>
        <el-option :value="15" label="5G专区"/>
        <el-option :value="16" label="官网首页banner"/>

      </el-select>
      <el-button v-permission="['POST /admin/ad/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/ad/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="广告ID" prop="id" sortable/>

      <el-table-column align="center" label="广告标题" prop="name"/>

      <el-table-column align="center" label="广告内容" prop="content"/>

      <el-table-column align="center" label="广告图片" prop="url">
        <template slot-scope="scope">
          <img v-if="scope.row.url" :src="scope.row.url" width="80">
        </template>
      </el-table-column>

      <el-table-column align="center" label="广告位置" prop="position">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.position==1" type="success">首页</el-tag>
          <el-tag v-if="scope.row.position==2" type="info">中间</el-tag>
          <el-tag v-if="scope.row.position==3" type="warning">良机优品页面</el-tag>
          <el-tag v-if="scope.row.position==4" type="warning">抢购</el-tag>
          <el-tag v-if="scope.row.position==5" type="warning">分类-新品展示</el-tag>
          <el-tag v-if="scope.row.position==6" type="warning">有好礼</el-tag>
          <el-tag v-if="scope.row.position==7" type="warning">首页广告</el-tag>
          <el-tag v-if="scope.row.position==8" type="warning">首页弹窗</el-tag>
          <el-tag v-if="scope.row.position==9" type="warning">通用配件</el-tag>
          <el-tag v-if="scope.row.position==10" type="warning">潮品</el-tag>
          <el-tag v-if="scope.row.position==11" type="warning">首页特权专栏</el-tag>
          <el-tag v-if="scope.row.position==12" type="warning">平板专栏</el-tag>
          <el-tag v-if="scope.row.position==13" type="warning">手机专栏</el-tag>
          <el-tag v-if="scope.row.position==14" type="warning">启动页广告</el-tag>
          <el-tag v-if="scope.row.position==15" type="warning">5G专区</el-tag>
          <el-tag v-if="scope.row.position==16" type="warning">官网首页banner</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="活动链接" prop="link"/>

      <el-table-column align="center" label="平台类型" prop="platformType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.platformType==0" type="success">所有平台</el-tag>
          <el-tag v-if="scope.row.platformType==1" type="success">app</el-tag>
          <el-tag v-if="scope.row.platformType==2" type="success">小程序</el-tag>
          <el-tag v-if="scope.row.platformType==3" type="success">H5</el-tag>
          <el-tag v-if="scope.row.platformType==4" type="success">APP+小程序</el-tag>
          <el-tag v-if="scope.row.platformType==5" type="success">APP+H5</el-tag>
          <el-tag v-if="scope.row.platformType==6" type="success">小程序+H5</el-tag>
          <el-tag v-if="scope.row.platformType==7" type="success">IOS</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="跳转类型" prop="linkType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.linkType==1" type="success">链接跳转</el-tag>
          <el-tag v-if="scope.row.linkType==2" type="success">商品ID跳转</el-tag>
          <el-tag v-if="scope.row.linkType==3" type="success">邀请好友</el-tag>
          <el-tag v-if="scope.row.linkType==4" type="success">首页楼层ID跳转</el-tag>
          <el-tag v-if="scope.row.linkType==5" type="success">锐利特权</el-tag>
          <el-tag v-if="scope.row.linkType==6" type="success">商品分类ID跳转</el-tag>
          <el-tag v-if="scope.row.linkType==7" type="success">商品列表页</el-tag>
          <el-tag v-if="scope.row.linkType==8" type="success">合伙人中心</el-tag>
          <el-tag v-if="scope.row.linkType==9" type="success">积分商城</el-tag>
          <el-tag v-if="scope.row.linkType==10" type="success">砍价列表</el-tag>
          <el-tag v-if="scope.row.linkType==11" type="success">二级分类列表</el-tag>
          <el-tag v-if="scope.row.linkType==12" type="success">文章</el-tag>
          <el-tag v-if="scope.row.linkType==13" type="success">团购</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否需要登陆" prop="needLogin">
        <template slot-scope="scope">
          <el-tag :type="scope.row.needLogin ? 'success' : 'error' ">{{ scope.row.needLogin ? '需要' : '不需要' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否启用" prop="enabled">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'error' ">{{ scope.row.enabled ? '启用' : '不启用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" prop="sortOrder"/>
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/ad/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/ad/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="广告标题" prop="name">
          <el-input v-model="dataForm.name"/>
        </el-form-item>
        <el-form-item label="广告内容" prop="content">
          <el-input v-model="dataForm.content"/>
        </el-form-item>
        <el-form-item label="广告图片" prop="url">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadUrl"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.url" :src="dataForm.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告位置" prop="position">
          <el-select v-model="dataForm.position" placeholder="请选择">
            <el-option :value="1" label="首页"/>
            <el-option :value="2" label="中间"/>
            <el-option :value="3" label="良机优品页面"/>
            <el-option :value="4" label="抢购"/>
            <el-option :value="5" label="分类-新品展示"/>
            <el-option :value="6" label="有好礼"/>
            <el-option :value="7" label="首页广告"/>
            <el-option :value="8" label="首页弹窗"/>
            <el-option :value="9" label="通用配件"/>
            <el-option :value="10" label="潮品"/>
            <el-option :value="11" label="首页特权专栏"/>
            <el-option :value="12" label="平板专栏"/>
            <el-option :value="13" label="手机专栏"/>
            <el-option :value="14" label="启动页广告"/>
            <el-option :value="15" label="5G专区"/>
            <el-option :value="16" label="首页官网banner"/>

          </el-select>
        </el-form-item>
        <el-form-item label="平台类型" prop="platformType">
          <el-select v-model="dataForm.platformType" placeholder="请选择">
            <el-option :value="0" label="所有平台"/>
            <el-option :value="1" label="app"/>
            <el-option :value="2" label="小程序"/>
            <el-option :value="3" label="H5"/>
            <el-option :value="4" label="APP+小程序"/>
            <el-option :value="5" label="APP+H5"/>
            <el-option :value="6" label="小程序+H5"/>
            <el-option :value="7" label="IOS"/>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转类型" prop="linkType">
          <el-select v-model="dataForm.linkType" placeholder="请选择">
            <el-option :value="1" label="链接跳转"/>
            <el-option :value="2" label="商品ID跳转"/>
            <el-option :value="3" label="邀请好友"/>
            <el-option :value="4" label="首页楼层ID跳转"/>
            <el-option :value="5" label="锐利特权"/>
            <el-option :value="6" label="商品分类ID跳转"/>
            <el-option :value="7" label="商品列表页"/>
            <el-option :value="8" label="合伙人中心"/>
            <el-option :value="9" label="积分商城"/>
            <el-option :value="10" label="砍价列表"/>
            <el-option :value="11" label="二级分类列表"/>
            <el-option :value="12" label="文章"/>
            <el-option :value="13" label="团购"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType === 1 || dataForm.linkType ===3 " label="请输入跳转链接" prop="link">
          <el-input v-model="dataForm.link"/>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType === 2" label="跳转链接" prop="link" >
          <el-select v-model="dataForm.link" filterable placeholder="请选择/输入跳转商品名称" >
            <el-option
              v-for="item in goodsListsAll"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType ===4 " label="跳转链接" prop="link">
          <el-select v-model="dataForm.link" filterable placeholder="请选择/输入首页楼层名称">
            <el-option
              v-for="item in homeCategory"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType === 6" label="跳转链接" prop="link" >
          <el-select v-model="dataForm.link" filterable placeholder="选择/输入商品分类名称">
            <el-option
              v-for="item in goodsCategory"
              :key="item.id"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType === 7" label="输入楼层枚举名称" prop="link">
          <el-input v-model="dataForm.link"/>
        </el-form-item>

        <el-form-item v-if="dataForm.linkType === 11" label="输入二级分类ID" prop="link">
          <el-input v-model="dataForm.link"/>
        </el-form-item>

        <el-form-item label="是否需要登录" prop="needLogin">
          <el-select v-model="dataForm.needLogin" placeholder="请选择">
            <el-option :value="true" label="需要"/>
            <el-option :value="false" label="不需要"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="dataForm.enabled" placeholder="请选择">
            <el-option :value="true" label="启用"/>
            <el-option :value="false" label="不启用"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="dataForm.sortOrder"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listAd, createAd, updateAd, deleteAd } from '@/api/ad'
import { listCatL1 } from '@/api/category'
import { listCategory } from '@/api/homeCategory'
import { listGoods } from '@/api/goods'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Ad',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      list: undefined,
      goodsListsAll: undefined,
      homeCategory: undefined,
      goodsCategory: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        content: undefined,
        position: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: undefined,
        content: undefined,
        url: undefined,
        link: undefined,
        position: 1,
        enabled: true
      },
      listQueryHomeCategory: {
        marketingType: 0,
        page: 1,
        limit: 500,
        sort: 'add_time',
        order: 'desc'
      },
      listQueryGoodsList: {
        page: 1,
        limit: 2000,
        sort: 'add_time',
        order: 'desc'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '广告标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '广告内容不能为空', trigger: 'blur' }
        ],
        url: [{ required: true, message: '链接图片不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    // this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listAd(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        content: undefined,
        url: undefined,
        link: undefined,
        position: 1,
        enabled: true
      }
    },
    operationData() {
      listCategory(this.listQueryHomeCategory)
        .then(response => {
          this.homeCategory = response.data.data.items
        })
        .catch(() => {
          this.homeCategory = []
        })
      listGoods(this.listQueryGoodsList)
        .then(response => {
          console.log(response)
          this.goodsListsAll = response.data.data.items
        })
        .catch(() => {
          this.goodsListsAll = []
        })
      listCatL1()
        .then(response => {
          this.goodsCategory = response.data.data
        })
        .catch(() => {
          this.goodsCategory = []
        })
    },
    handleCreate() {
      this.resetForm()
      this.operationData() // 加载数据
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadUrl: function(response) {
      this.dataForm.url = response.data.url
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createAd(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.operationData() // 加载数据
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateAd(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新广告成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该条广告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAd(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '广告ID',
          '广告标题',
          '广告内容',
          '广告图片',
          '广告位置',
          '活动链接',
          '是否启用'
        ]
        const filterVal = [
          'id',
          'name',
          'content',
          'url',
          'postion',
          'link',
          'enabled'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '广告信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
